<?php

namespace app\admin\model;

use think\Db;
use think\Exception;
use think\Model;


class Questioncategory extends Model
{


    // 表名
    protected $name = 'course_question_category';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * getListByCourseId
     * @param $course_id
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getListByCourseId($course_id)
    {
        $where = [
            'course_id' => $course_id,
        ];
        return $this->where($where)->order('weigh desc,id asc')->select();
    }

    /**
     * @throws Exception
     */
    public function createDefaultCategory($courseId)
    {
        // 时间
        $time = time();
        
        // 一级
        $this->createLevel1($time, $courseId);

        // 二级
        $this->createLevel23($time, $courseId);
    }

    /**
     * createLevel1
     * @param $time
     * @param $courseId
     * @return void
     * @throws Exception
     */
    private function createLevel1($time, $courseId)
    {
        $level1 = [
            [
                'pid' => 0,
                'name' => '默认分类',
                'level' => 1,
                'weigh' => 10,
                'status' => 1,
                'course_id' => $courseId,
                'tag_id' => 0,
                'create_time' => $time,
                'update_time' => $time
            ],
            [
                'pid' => 0,
                'name' => 'XXXX',
                'level' => 1,
                'weigh' => 20,
                'status' => 1,
                'course_id' => $courseId,
                'tag_id' => 30,
                'create_time' => $time,
                'update_time' => $time
            ],
            [
                'pid' => 0,
                'name' => 'XXXX',
                'level' => 1,
                'weigh' => 10,
                'status' => 1,
                'course_id' => $courseId,
                'tag_id' => 40,
                'create_time' => $time,
                'update_time' => $time
            ]
        ];

        // 循环一级
        foreach ($level1 as $k => $v) {
            $isSave = $this->save($v);
            if ($isSave === false) {
                throw new Exception('保存一级分类失败');
            }
        }
    }

    /**
     * createLevel23
     * @param $time
     * @param $courseId
     * @return void
     * @throws Exception
     */
    private function createLevel23($time, $courseId)
    {
        // config level23 tag
        $allTags = [
            ['id' => 30, 'name' => 'xxx', 'level' => 1],
            ['id' => 40, 'name' => 'xxx', 'level' => 1],
            ['id' => 30, 'name' => 'xxx', 'level' => 2],
            ['id' => 40, 'name' => 'xxx', 'level' => 2],
        ];
        foreach ($allTags as $k => $v) {
            //001.find tag category
            $where = ['course_id' => $courseId, 'tag_id' => $v['id'], 'level' => $v['level']];
            $tagCategory = $this->where($where)->find();
            if (!$tagCategory) {
                throw new Exception('find tag category');
            }

            //002.create tag child
            $tagChild = [
                'pid' => $tagCategory['id'],
                'name' => $v['name'],
                'level' => $v['level'] + 1,
                'weigh' => 10,
                'status' => 1,
                'course_id' => $courseId,
                'tag_id' => $v['id'],
                'create_time' => $time,
                'update_time' => $time
            ];
            $isSave = $this->save($tagChild);
            if ($isSave === false) {
                throw new Exception('create tag child failed');
            }
        }
    }
}
